package javavis;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.StreamTokenizer;

import javavis.jip3d.geom.Point3D;

/**
*   This executable class allow to convert files with 3D information into our format
*/
public class Convert3DPoints {
	/**
	 * Directory where to apply the cleaning
	 * @uml.property  name="dir"
	 */
	private String dir;

	
	/** Constructor. */
	public Convert3DPoints(String idir) {
		dir=idir;
	}

	/**
	 * Shows an error and help lines in standard error output.
	 * @param str Error to show.
	 */
	public void error(String str) {
		System.err.println("*** ERROR: " + str + " ***");
		help();
	}

	/**
	* It shows in the standard error output the function help lines.
	*/
	static public void help() {
		System.out.println("Usage:");
		System.out.println("    java Convert3DPoints dir");
		System.out.println("  where dir is the directory to process.");
	}
	
	/**
	 * Execute the cleaning
	 */
	public void execute () {
		File f = new File(dir);
		String []files = f.list();
		Reader fr;
		StreamTokenizer st;
		int num_puntos;
		boolean yInverted;
		int isColor;
		FileWriter fw;

		for (String fi : files)
			if (fi.matches("\\w*.p3d")) {
				System.out.println("Processing "+fi);

				try {
					String aux=new String();
					fr=new FileReader(dir+"//"+fi);
					st=new StreamTokenizer(fr);

					st.nextToken();
					char c=(char)st.ttype;
					aux += c;
					st.nextToken();
					aux += st.sval;
					aux += "\n";
					st.nextToken();
					num_puntos=(int)st.nval;
					aux += (int)st.nval;
					st.nextToken();
					isColor=3;
					st.nextToken();
					yInverted=false;
					aux += " 3 1 0\n"; // Here we can write our desire output
					st.nextToken();
					c=(char)st.ttype;
					aux += c;
					st.nextToken();
					aux += st.sval;
					aux += "\n";
					
					Point3D[] ps = new Point3D[num_puntos];

					for(int cont=0;cont<num_puntos;cont++) {
						ps[cont] = new Point3D(st, isColor, true, yInverted);
					}
					fr.close();

					fw = new FileWriter(dir+"//"+fi);
					fw.write(aux);
					for(int cont=0;cont<num_puntos;cont++) {
						fw.write(ps[cont].toStringRGB()+"\n");
					}
					fw.close();

				} catch (IOException e)
				{
					System.out.println("Convert3DPoints::readData Error: can not read data from "+dir+"//"+fi);
					return;
				}
			}
	}

	public static void main(String[] args) {
		if (args==null || args.length==0) {
			Convert3DPoints.help();
			System.exit(-1);
		}
		Convert3DPoints lau = new Convert3DPoints(args[0]);
		lau.execute();
		System.exit(0);
	}
}
